package com.ruitaowang.admin.websocket;

import com.ruitaowang.core.domain.UserOnline;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.UserOnlineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;


public class WebSocketDisconnectHandler<S>
		implements ApplicationListener<SessionDisconnectEvent> {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketDisconnectHandler.class);
	private SimpMessageSendingOperations messagingTemplate;
	private UserOnlineService userOnlineService;

	public WebSocketDisconnectHandler(SimpMessagingTemplate messagingTemplate,
									  UserOnlineService userOnlineService){
		super();
		this.messagingTemplate = messagingTemplate;
		this.userOnlineService = userOnlineService;
	}

	public void onApplicationEvent(SessionDisconnectEvent event) {
		MessageHeaders headers = event.getMessage().getHeaders();
		Principal user = SimpMessageHeaderAccessor.getUser(headers);
		LOGGER.debug("user {}", user);
		if(user==null || user.getName()==null || user.getName().split("-").length != 2){
			return;
		}
		LOGGER.debug("user.name {}", user.getName());
		LOGGER.debug("id {} 退出了。", event.getSessionId());
		userOnlineService.updateByUserIdAndRoomId(Long.valueOf(user.getName().split("-")[0]), Long.valueOf(user.getName().split("-")[1]), (byte) 1);
//		this.messagingTemplate.convertAndSend("/topic/online/"+user.getName().split("-")[1], MsgOut.success(-1));
	}
}
